part of 'index.dart';

class VideoPlayerPage extends StatefulWidget {
  const VideoPlayerPage(this.msgId, {super.key, this.localUrl});
  final String msgId;
  final String? localUrl;

  @override
  State<VideoPlayerPage> createState() => _VideoPlayerPageState();
}

class _VideoPlayerPageState extends State<VideoPlayerPage> {
  chat.Message? message;
  VideoPlayerController? _controller;
  bool _isLoading = true;
  bool _hasError = false;
  bool _isPlaying = true;

  @override
  void initState() {
    super.initState();
    EMClient.getInstance.chatManager.addMessageEvent(
      "vp_send_message_change_listener",
      ChatMessageEvent(
        onSuccess: (msgId, msg) {
          debugPrint("==IM==:消息上传或下载成功($msgId)");
          if (message != null && msgId == message!.msgId) {
            final body = message!.body as EMVideoMessageBody;
            final local = body.localPath;
            if (local.isNotEmpty) {
              final file = File(local);
              _initVideoPlayer(file);
            }
          }
        },
        onProgress: (msgId, progress) {},
        onError: (msgId, msg, error) {
          debugPrint(
              "==IM==:发送消息失败, code: ${error.code}, desc: ${error.description}");
          if (message != null && msgId == message!.msgId && mounted) {
            setState(() {
              _isLoading = false;
              _hasError = true;
            });
          }
        },
      ),
    );
    _init();
  }

  @override
  void dispose() {
    // 移除监听器
    EMClient.getInstance.chatManager
        .removeMessageEvent("vp_send_message_change_listener");
    _controller?.dispose();
    super.dispose();
  }

  void _init() async {
    message = await ImManager.of.findMessage(msgId: widget.msgId);
    if ((message == null || message?.body == null) && widget.localUrl == null) {
      setState(() {
        _isLoading = false;
        _hasError = true;
      });
      return;
    }
    final body = message?.body as EMVideoMessageBody?;
    var local = body?.localPath;
    if (widget.localUrl?.isNotEmpty == true) local = widget.localUrl!;
    final remote = body?.remotePath;

    try {
      if (local?.isNotEmpty == true) {
        final file = File(local!);
        if (await file.exists()) {
          // 本地文件存在，直接播放
          _initVideoPlayer(file);
        } else {
          // 本地文件不存在，需要下载
          // 开始下载，下载完成后会通过监听器回调处理
          await ImManager.of.downloadAttachment(message: message!);
        }
      } else if (remote != null && remote.startsWith('http')) {
        // 如果有远程URL，直接使用网络播放
        _controller = VideoPlayerController.networkUrl(Uri.parse(remote));
        await _controller!.initialize();
        await _controller!.play();
        setState(() {
          _isLoading = false;
        });
      } else {
        throw Exception('视频路径为空');
      }
    } catch (e) {
      debugPrint('视频播放初始化失败: $e');
      setState(() {
        _isLoading = false;
        _hasError = true;
      });
    }
  }

  // 初始化视频播放器
  void _initVideoPlayer(File file) async {
    try {
      if (!mounted) return;

      _controller = VideoPlayerController.file(file);
      // 添加视频播放完成监听
      _controller!.addListener(_videoListener);
      await _controller!.initialize();
      await _controller!.play();
      _isPlaying = true;

      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    } catch (e) {
      debugPrint('视频播放器初始化失败: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
          _hasError = true;
        });
      }
    }
  }

  // 视频状态监听
  void _videoListener() {
    // 检测视频是否播放完成
    if (_controller != null &&
        _controller!.value.position >= _controller!.value.duration) {
      // 视频播放完成，重新开始播放
      if (mounted) {
        setState(() {
          _isPlaying = false;
        });
      }
    }
  }

  // 切换播放/暂停状态
  void _togglePlayPause() {
    if (_controller == null) return;

    setState(() {
      if (_controller!.value.isPlaying) {
        _controller!.pause();
        _isPlaying = false;
      } else {
        // 如果视频已经播放完成，先回到开始位置
        if (_controller!.value.position >= _controller!.value.duration) {
          _controller!.seekTo(Duration.zero);
        }
        _controller!.play();
        _isPlaying = true;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          if (_isLoading)
            const Center(child: CircularProgressIndicator())
          else if (_hasError)
            const Center(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Icon(Icons.error_outline, color: Colors.white, size: 48),
                  SizedBox(height: 16),
                  Text('视频加载失败', style: TextStyle(color: Colors.white)),
                ],
              ),
            )
          else if (_controller != null)
            GestureDetector(
              onTap: _togglePlayPause,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  Center(
                    child: AspectRatio(
                      aspectRatio: _controller!.value.aspectRatio,
                      child: VideoPlayer(_controller!),
                    ),
                  ),
                  // 播放/暂停按钮
                  if (!_isPlaying)
                    Container(
                      width: 60,
                      height: 60,
                      decoration: BoxDecoration(
                        color: Colors.black.withOpacity(0.5),
                        shape: BoxShape.circle,
                      ),
                      child: const Icon(
                        Icons.play_arrow,
                        color: Colors.white,
                        size: 40,
                      ),
                    ),
                ],
              ),
            ),

          // 关闭按钮
          Positioned(
            top: MediaQuery.of(context).padding.top + 16,
            left: 16,
            child: GestureDetector(
              onTap: () => Navigator.of(context).pop(),
              child: Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.black.withOpacity(0.5),
                  shape: BoxShape.circle,
                ),
                child: const Icon(Icons.close, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
